<template>
    <div class="page_root" :key="queryUpdateFlag" data-page-name="1" data-page-identification="x_hb0xe6o0k2">
        <a-spin :spinning="pageLoading.loading" :tip="pageLoading.tip">
            <div>
                {{ stateForm }}
            </div>
            <!-- end vid_q2pj193dfc 自定义模板_7xu4mdl9mj -->
        </a-spin>
    </div>
</template>
<script setup lang="tsx">
    import {
        h,
        ref,
        reactive,
        toRaw,
        markRaw,
        watch,
        computed,
        onBeforeMount,
        onMounted,
        onBeforeUnmount,
        onUnmounted,
        onActivated,
        onDeactivated
    } from 'vue'
    import { useRoute, useRouter } from 'vue-router'
    const router = useRouter()
    const route = useRoute()
    import { get, post, put, del, request, requestWithHeaders } from '@/utils/http/Axios'
    import {
        cloneDeep,
        localGet,
        merge,
        getDifferenceArray,
        traversalTreeStructure,
        checkCaseCondition,
        renderStringInTemplate,
        handleBreadcrumbJump,
        throttle,
        permission,
        getComponentParamsValue
    } from '@/utils/index'
    import { isNullOrEmpty, isEmptyArr, isNullOrUnDef, isContained, isArray, isEmpty, isObject } from '@/utils/is'
    import dayjs from 'dayjs'
    import { getPagePcChartsDataSourceConvert } from '@/utils/chart'
    import { message, notification, Modal } from 'ant-design-vue'
    import {
        propertyFormatByNumber,
        propertyFormatByPercentage,
        propertyFormatByDate,
        parseSubFromDataList
    } from '@/utils/format'
    import colorTheme from '@/design/custom-theme.json'
    /*** PUBLISH_EXEGESIS ***
 import UserTableRecords from '@/model/UserTableRecords';
 import { getAppBaseUrl } from '@/utils/index';
 import { sendToken } from "@/hooks/useIframeToken";
 import { useSystemStore } from "@/store/modules/system";
 const systemStore = useSystemStore();
 *** PUBLISH_EXEGESIS ***/

    // 获取传入的流程ID和组件参数
    const props = defineProps({
        'processInstanceId': {
            type: [String, Number, Boolean],
            default: undefined
        }
    })
    const immediateWatch = (source, callback) => {
        watch(source, callback, { deep: true, immediate: true })
    }

    /* -------------------------- 属性定义 -------------------------- */

    const setTimeOutList = []
    const pageLoading = reactive({
        loading: false,
        tip: undefined
    })
    const authInfo = localGet('app-user-store')

    // 处理校验
    const setSubFormName = (parentInfo, name) => {
        return [parentInfo.parents, parentInfo.cycleIndex, name]
    }

    /* ========================== 属性定义 ========================== */

    /* -------------------------- 元素数据引用 -------------------------- */

    /* ========================== 元素数据引用 ========================== */

    /* -------------------------- 页面数据 -------------------------- */

    /* ========================== 页面数据 ========================== */

    /* -------------------------- 响应 -------------------------- */

    /* ========================== 响应 ========================== */

    /* -------------------------- 函数 -------------------------- */

    /* ========================== 函数 ========================== */

    /* -------------------------- 页面参数 -------------------------- */

    const pageParameter_state = reactive({
        'processInstanceId': props.processInstanceId ?? route.query.processInstanceId
    })

    /* ========================== 页面参数 ========================== */

    /* -------------------------- 组件事件处理方法 -------------------------- */

    // ---------------------------- 组件数据同步 ----------------------------

    // ============================ 组件数据同步 ============================

    /* ========================== 组件事件处理方法 ========================== */

    /* -------------------------- 生命周期 -------------------------- */
    // 用于参数变更后重新执行自定义指令
    const queryUpdateFlag = ref(0)
    onMounted(() => {})

    onUnmounted(() => {
        // 销毁定时器
        setTimeOutList.forEach(({ repeat, timer }) => {
            repeat ? clearInterval(timer) : clearTimeout(timer)
        })
    })
    const projectId = ref(1654)
    const projectTemplate = ref('10987')
    /* ========================== 生命周期 ========================== */

    /* -------------------------- 数据关联处理 -------------------------- */

    /* -------------------------- 表单数据同步 -------------------------- */
    /* ========================== 表单数据同步 ========================== */

    /* ========================== 数据关联处理 ========================== */

    /* -------------------------- 不同组件自定义的处理逻辑 -------------------------- */

    /* ========================== 不同组件自定义的处理逻辑 ========================== */

    // ================================定制化逻辑========================================
    const stateForm = reactive({
        tenantId: null,
        sessionKey: null,
        userId: null,
        mobile: null,
        productId: null,
        getTidUrl: null,
        newUrl: null
    })
    const debuggerState = reactive({
        first: {
            status: '',
            content: ''
        },
        two: {
            status: '',
            content: ''
        },
        three: {
            status: '',
            content: ''
        },
        four: {
            status: '',
            content: ''
        },
        five: {
            status: '',
            content: ''
        }
    })
    // var currentURL = window.location.href
    var currentURL ='http://asa-qa.allintechinc.com/app_50000005/page/3000000356?sessionKey=third_party:session_key:15225745513&mobile=15225745513&userId=FengTengFei'
    function getParameterByName(name, url = window.location.href) {
        name = name.replace(/[\[\]]/g, '\\$&')
        var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'),
            results = regex.exec(url)
        if (!results) return null
        if (!results[2]) return ''
        return decodeURIComponent(results[2].replace(/\+/g, ' '))
    }
    stateForm.sessionKey = getParameterByName('sessionKey', currentURL)
    stateForm.userId = getParameterByName('userId', currentURL)
    stateForm.mobile = getParameterByName('mobile', currentURL)
    // 获取当前页面url的传参
    async function getTenantId() {
        try {
            debuggerState.two.status = '第二步获取tenantId开始'
            let firstSlashIndex = currentURL.indexOf('/', 8)
            let prefix

            if (firstSlashIndex !== -1) {
                prefix = currentURL.substring(0, firstSlashIndex)
                let protocols = ['http://', 'https://']
                let protocol = protocols.find(p => prefix.includes(p))

                if (protocol) {
                    let result = prefix.substring(protocol.length)
                    result = result + '/app_50000005/'
                    console.log(result, 'result')
                    let data = await post(`/base/api/v1/product/url`, {
                        url: result
                        // url: 'ppm-stage.allintechinc.com'
                    })
                    if (data.status === 'success') {
                        // 获取到的tenantId
                        stateForm.tenantId = data.data.tenantId
                        stateForm.productId = data.data.id
                        // 成功获取之后登陆操作
                        debuggerState.two.content = `第二步成功-----tenantId是${data.data.tenantId},productId是${data.data.id}`
                        getToken()
                    } else {
                        console.error('获取tenantId失败')
                        debuggerState.two.content = `获取tenantId失败${data.errorMsg},传值是${result}`
                    }
                } else {
                    console.error('未找到 `http://` 或 `https://`')
                }
            } else {
                console.error('无法提取前缀')
            }
        } catch (error) {
            console.error('getTenantId出现错误:', error)
        }
    }
    import { useUserStoreWithOut } from '@/store/modules/user'
    const userStore = useUserStoreWithOut()
    import { resetRouter } from '@/router'
    import { asyncRoutes } from '@/router/routes'
    import type { Router, RouteRecordRaw } from 'vue-router'
    async function getToken() {
        try {
            debuggerState.five.status = '第五步登录获取信息'
            let uuid = ''
            let token = ''
            const params = {
                sessionKey: stateForm.sessionKey,
                mobile: stateForm.mobile,
                appId: 'product-container',
                withTenantIdFlag: false,
                mobileIsUserName: false,
                tenantId: stateForm.tenantId
            }
            let result = await post('/base/api/v1/open/login', params)
            console.log(result.status, 'getTokenstatus')
            if (result.data) {
                console.log(result, '登陆接口返回')
                debuggerState.five.content = `第五步登录获取信息--登陆接口返回${result}`
                let newUserData = {
                    uuid: result.data.uuid,
                    token: result.data.token,
                    productId: stateForm.productId,
                    tenantId: stateForm.tenantId,
                    appid: 'product-container'
                }
                localStorage.setItem('app-user-store', JSON.stringify(newUserData))
                localStorage.setItem('app-user', JSON.stringify(newUserData))
                localStorage.setItem(
                    'al__Access-Token',
                    JSON.stringify({
                        expire: new Date().getTime(),
                        value: result.data.token
                    })
                )
                localStorage.setItem(
                    'al__UID',
                    JSON.stringify({
                        expire: new Date().getTime(),
                        value: result.data.uuid
                    })
                )
                uuid = result.data.uuid
                token = result.data.token
                console.log('登录后执行跳转')
                // const userInfo = await get('/base/api/v1/user/userinfo', null, {
                //     headers: {
                //         'token': token,
                //         uid: uuid
                //     }
                // })
                // const userInfo = await get('/base/api/v1/user/userinfo')

                // if (userInfo.data) {
                //     const { userItem } = userInfo.data
                //     userStore.setUserInfo(userItem)
                //     userStore.buildPermissionInfo(userInfo.data.resourcesItems)
                //     console.log(userStore, 'userStore')
                //     // 构建路由信息
                //     // 基于用户权限信息构建路由
                //     resetRouter()
                //     asyncRoutes.forEach(route => {
                //         router.addRoute(route as unknown as RouteRecordRaw)
                //     })
                //     // 获取用户信息后，如果目标页是403页，跳到首页
                //     // if (to.name === ROUTER_NAME.PAGE_NO_ACCESS) {
                //     //     next({ name: ROUTER_NAME.PAGE_ROOT, params: to.params, replace: true })
                //     // }
                //
                //     setTimeout(() => {
                //         window.location.href = `${import.meta.env.VITE_PUBLIC_PATH}/page/3000000356`
                //         // window.open( `${import.meta.env.VITE_PUBLIC_PATH}/page/3000000356`,'_blank')
                //         // router.push(`${import.meta.env.VITE_PUBLIC_PATH}/page/3000000356`) // 使用router进行跳转
                //     }, 2000)
                // }
                debuggerState.five.status = '第五步登录获取信息--跳转成功'
              setTimeout(() => {
                window.location.href = `${import.meta.env.VITE_PUBLIC_PATH}/page/3000000356`
                // window.open( `${import.meta.env.VITE_PUBLIC_PATH}/page/3000000356`,'_blank')
                // router.push(`${import.meta.env.VITE_PUBLIC_PATH}/page/3000000356`) // 使用router进行跳转
              }, 2000)
                //   window.location.href = stateForm.getTidUrl;
            } else {
                console.error('getToken出现错误:')
                debuggerState.five.content = `第五步登录获取信息--失败${result.errorMsg}`
            }
        } catch (error) {
            console.error('getToken出现错误:', error)
            message.error('登录失败', error)
            debuggerState.five.content = `第五步登录获取信息--失败${error}`
        }
    }
    getTenantId()
    onMounted(() => {
        localStorage.removeItem('app-user-store')
        localStorage.removeItem('app-user')
        console.log('清除')
        console.log(localStorage.getItem('app-user-store'))
    })
</script>
<style lang="less" scoped>
    .page_root {
        width: 100%;
        height: 100%;
        overflow: auto;
    }
    .page_root :deep(.@{ant-prefix}-spin-nested-loading),
    .page_root :deep(.@{ant-prefix}-spin-container) {
        height: 100%;
    }
    .page_root :deep(.@{ant-prefix}-spin-container .@{ant-prefix}-table-wrapper) {
        display: flex;
        flex-flow: column nowrap;
        justify-content: flex-start;
    }
    .page_root :deep(.@{ant-prefix}-table) {
        flex: auto;
        overflow: auto;
    }
    .table-moreBtn_down {
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
        width: 100px;
    }

    .table-moreBtn_menu :deep(.table-moreBtn_menu-item):hover {
        background: #ebf1ff;
    }

    /*  表格树结构样式处理，展开按钮层级增加*/
    :deep(.@{ant-prefix}-table-row-expand-icon) {
        z-index: 1;
    }
    /*  表格树结构 由于每个表格项采用自定义组件，使用绝对定位布局，开启树结构导致显示异常，暂时使用层级定位位置 */
    :deep(.@{ant-prefix}-table-row-level-1 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
        left: 15px !important;
        width: calc(100% - 15px);
    }
    :deep(.@{ant-prefix}-table-row-level-2 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
        left: 30px !important;
        width: calc(100% - 30px);
    }
    :deep(.@{ant-prefix}-table-row-level-3 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
        left: 45px !important;
        width: calc(100% - 45px);
    }
    :deep(.@{ant-prefix}-table-row-level-4 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
        left: 60px !important;
        width: calc(100% - 60px);
    }

    /* 穿梭框改变默认样式，为根据组件样式控制左右栏宽度。 */
    :deep(.@{ant-prefix}-transfer-list) {
        height: 100%;
        width: 50%;
    }

    /*新任务*/
    .new-task-title {
        height: 30px;
        border-bottom: 1px solid #bfbfbf;
        margin-bottom: 16px;
    }

    .new-task-title-son {
        font-family: PingFangSC-Semibold;
        font-size: 14px;
        color: #262626;
        letter-spacing: 0;
        font-weight: 600;
        border-left: 4px solid #3875ff;
        padding-left: 5px;
        height: 18px;
        line-height: 18px;
    }
    .mbtask-form :deep(.ant3-form-item-label) {
        width: 115px !important;
    }
    /*新任务*/
    .ant3-image-preview .ant3-image-preview-img-wrapper {
        position: relative !important;
    }
</style>
